﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace xfTasker
{
    /// <summary>
    /// 定时器
    /// </summary>
    public class Tasker
    {
        public delegate void DoTaskHandler(object sender);
        /// <summary>
        /// 事件(sender,msg)，执行成功返回"1"，失败返回异常信息。
        /// </summary>
        public event DoTaskHandler DoTask;

        private static Tasker _Tasker = null;
        private Timer UpdateTimer = null; 
        private int _IsRunning;
        
        private int _interval = 1000;
        /// <summary>
        /// 执行间隔,默认1000,1秒
        /// </summary>
        public int Interval
        {
            get { return _interval;}
            set { _interval = value; }
        }

        /// <summary>
        /// 每次创建一个Tasker
        /// </summary>
        public Tasker()
        {

        }
        /// <summary>
        /// 单例，用于开启和关闭都是同一个Tasker
        /// </summary>
        /// <returns></returns>
        public static Tasker Instance()
        {
            if (_Tasker != null) return _Tasker;
            else
            {
                _Tasker = new Tasker();
            }
            return _Tasker;
        }


        public void Start()
        {
            if (UpdateTimer == null)
            {
                UpdateTimer = new Timer(new TimerCallback(UpdateTimerCallback), null, _interval, _interval);
            }

        }
           
        private void UpdateTimerCallback(object sender)
        {
            if (Interlocked.Exchange(ref _IsRunning, 1) == 0)
            {
                try
                {
                    DoTask(sender);
                }
                catch (Exception ex)
                {
                    
                }
                finally
                {
                    Interlocked.Exchange(ref _IsRunning, 0);
                }
            }
        }

        public void Stop()
        {
            if (UpdateTimer != null)
            {
                UpdateTimer.Dispose();
                UpdateTimer = null;
            }
        }
    }


}
